//
//  DuanziTableView.m
//  item-NetEaseNews-tyw
//
//  Created by tyw on 15/10/1.
//  Copyright (c) 2015年 tyw. All rights reserved.
//

#import "DuanziTableView.h"
#import "DuanziModel.h"
#import "DuanziTableViewCell.h"
#import "NewsViewController.h"
#import "DuanziModel.h"
#import "NewsDetailViewController.h"

@implementation DuanziTableView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.delegate = self;
        self.dataSource = self;
        self.userInteractionEnabled = YES;
        
        self.backgroundColor = [UIColor clearColor];
        
        [self registerClass:[DuanziTableViewCell class] forCellReuseIdentifier:kDuanziTableViewCellId];
    }
    
    return self;
}

- (void)setDuanziModelArray:(NSArray *)duanziModelArray {
    _duanziModelArray = [duanziModelArray copy];
    
    [self reloadData];
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _duanziModelArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    DuanziTableViewCell* cell = [self dequeueReusableCellWithIdentifier:kDuanziTableViewCellId forIndexPath:indexPath];
    
    DuanziModel* model = [[DuanziModel alloc] initWithDataDic:_duanziModelArray[indexPath.row]];
    cell.duanziModel = model;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    DuanziModel* model = [[DuanziModel alloc] initWithDataDic:_duanziModelArray[indexPath.row]];
    
    NSString* content = model.content;
    
    CGFloat height =  [Tools contentSizeWithMaxWidth:kWidth-20 text:content fontOfSize:14].height;
    
    //根据段子内容自适应文本高度
    if ([model.imgType boolValue]) {            //如果有图片，就算上图片的高度,给个250
        return height+70+250;
    } else {                                    //没有图片
        return height+70;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    //通过响应者链,找到newsVC
    NewsViewController* newsVC = [Tools className:@"NewsViewController" fromResponder:self.nextResponder];
    
    if (newsVC) {
        DuanziModel* model = [[DuanziModel alloc] initWithDataDic:_duanziModelArray[indexPath.row]];
        
        NewsDetailViewController* newsDetailVC = [[NewsDetailViewController alloc] init];
        if (model.duanziId.length) {
            newsDetailVC.newsId = model.duanziId;
            newsDetailVC.replyId = model.replyId;
            [newsVC.navigationController pushViewController:newsDetailVC animated:YES];
        }
    }
    
}

@end
